package com.share.device.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.share.common.core.exception.ServiceException;
import com.share.device.service.IMapService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class IMapServiceImpl implements IMapService {

    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tencent.map.key}")
    private String key;


    @Override
    public JSONObject calculateLatLng(String keyword) {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/?address="+keyword+"&key="+key;
        Request request = new Request.Builder().url(url).get().build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("地图API调用失败，状态码: {}", response.code());
                throw new ServiceException("地图服务调用失败");
            }

            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                log.error("地图API返回空响应");
                throw new ServiceException("地图服务返回空数据");
            }

            JSONObject jsonResponse = JSONObject.parseObject(responseBody.string());
            int status = jsonResponse.getIntValue("status");

            if (status != 0) {
                log.error("地图API返回异常状态，状态码: {}，消息: {}", status, jsonResponse.getString("message"));
                throw new ServiceException("地图解析异常: " + jsonResponse.getString("message"));
            }

            JSONObject result = jsonResponse.getJSONObject("result");
            if (result == null) {
                log.error("地图API返回结果为空");
                throw new ServiceException("地图服务未返回有效结果");
            }

            log.debug("地图API调用成功，返回结果: {}", result.toJSONString());
            return result.getJSONObject("location");

        } catch (IOException e) {
            log.error("调用地图API时发生IO异常，关键词: {}", keyword, e);
            throw new ServiceException("网络连接异常，请稍后重试");
        } catch (Exception e) {
            log.error("调用地图API时发生未知异常，关键词: {}", keyword, e);
            throw new ServiceException("地图服务暂时不可用");
        }
    }

    @Override
    public Double calculateDistance(String startLongitude, String startLatitude, String endLongitude,
                                    String endLatitude) {
        String url = "https://apis.map.qq.com/ws/direction/v1/walking/?from={from}&to={to}&key={key}";



        Map<String, String> map = new HashMap<>();
//        map.put("from", startLongitude + "," + startLatitude);
//        map.put("to", endLongitude + "," + endLatitude);
        map.put("from", startLatitude + "," + startLongitude);
        map.put("to", endLatitude + "," + endLongitude);
//        map.put("from", "39.915285,116.403857");
//        map.put("to", "39.915285,116.406857");
        map.put("key", key);

        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        log.info("地图API调用成功，返回结果: {},{}", result.toJSONString(), map);
        if(result.getIntValue("status") != 0) {
            log.error("地图API返回异常状态，状态码: {}，消息: {}", result.getIntValue("status"), result.getString("message"));
            throw new ServiceException("地图服务调用失败");
        }
        // 检查routes数组是否存在且不为空
        JSONObject resultObj = result.getJSONObject("result");
        if (resultObj == null) {
            log.error("地图API返回结果为空");
            throw new ServiceException("地图服务未返回有效路线");
        }

        com.alibaba.fastjson2.JSONArray routes = resultObj.getJSONArray("routes");
        if (routes == null || routes.isEmpty()) {
            log.warn("地图API未返回有效路线，起点: {}, 终点: {}",
                    map.get("from"), map.get("to"));
            // 返回默认距离值，如0或根据业务需求处理
            return 0.0;
        }

        // 返回第一条最佳线路
        JSONObject route = routes.getJSONObject(0);
        return route.getBigDecimal("distance").doubleValue();
    }


}
